# -*- coding: utf-8 -*-
# @Author : zhaochen
# @Date   : 2019/4/18
# @File   : R22_Ind_UnpaidOverdueCnt_6monCheck.py
# @E-mail : zhaochen@bbdservice.com

'''eof
name:申请人近半年内未结清业务逾期次数校验
code:Ind_UnpaidOverdueCnt_6monCheck_2D
tableName:
columnName:
groups:准入>个人征信校验
dependencies:IC_DSJ_2D
type:常用指标
datasourceType:在线指标
description:
eof'''


import sys
import datetime

reload(sys)
sys.setdefaultencoding('utf-8')

null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--']

def getTable(data, tableName, occurTimes):
    '''
        获取表信息
        :param data:表上层的字典对象
        :param tableName:表的名字
        :param occurTimes:表出现的次数，如果是0代表此表可以不出现，如果是1代表此表必须出现
        :return:该表全部数据
        '''
    table = data.get(tableName)
    if occurTimes == 0:
        if table is None:
            return [{}]
        elif table == "":
            return ""
        elif isinstance(table, list) is False or len(table) == 0:
            return None
        else:
            return data.get(tableName)

    if occurTimes == 1:
        if table == "":
            return ""
        if table is None or isinstance(table, list) is False or len(table) == 0:
            return None
        elif len(table) == 0:
            return [{}]
        else:
            return data.get(tableName)

def isfloat(x):
    '''
    判断x为float类型且大于等于0
    '''
    try:
        if isinstance(float(x), float) and float(x) >= 0:
            if str(x) in ['inf', 'infinity', 'INF', 'INFINITY', 'True']:
                return False
            else:
                return True
        else:
            return False
    except:
        return False


#借贷账户信息  PDA  [1..1]  借贷账户信息单元  PD01  [0..*]
# 基本信息段  PD01A  [1..1]  $账户类型  PD01AD01  [1..1]
# 最新表现信息段  PD01B  [1..1] $账户状态  PD01BD01  [1..1]
#
# 最近 5 年内历史表现信息段  PD01E  [0..1]
# 历史表现信息  PD01EH  [1..60] $还款状态  PD01ED01 [1..1]\逾期（透支）总额  PD01EJ01  [1..1]

def Ind_UnpaidOverdueCnt_6monCheck():
    data = IC_DSJ_2D['data']
    PDA = getTable(data, 'PDA', occurTimes=1)
    if PDA is None:
        return u'缺失值'
    elif PDA == [{}] or PDA == "":
        return 1 # 表示通过
    else:
        PD01 = getTable(PDA[0], 'PD01', occurTimes=0)
        if PD01 is None or PD01 == "":
            return None
        elif PD01 == [{}]:
            return 1 # 表示通过
        else:
            # 存记录数 还款状态为1的记录数
            result1 = []
            # 存最大值 还款状态的最大值
            result2 = []
            for p2 in PD01:
                PD01A = getTable(p2, 'PD01A', 1)
                PD01B = getTable(p2, 'PD01B', 1)
                PD01E = getTable(p2, 'PD01E', 0)
                if PD01A in null_type_list or PD01B in null_type_list or PD01E in null_type_list:
                    result1.append(None)
                    result2.append(None)
                elif PD01E == [{}]:
                    result1.append(0)
                    result2.append(0)
                else:
                    # 账户类型 必须有
                    accountType = PD01A[0].get('PD01AD01')
                    # 账户状态 必须有
                    accountState = PD01B[0].get('PD01BD01')
                    PD01EH = getTable(PD01E[0], 'PD01EH', 1)

                    if accountType in null_type_list or accountState in null_type_list or PD01EH in null_type_list:
                        result1.append(None)
                        result2.append(None)
                        continue
                    elif PD01EH == [{}]:
                        result1.append(0)
                        result2.append(0)
                    else:
                        monthToday = datetime.datetime.now().year * 12 + datetime.datetime.now().month
                        monthSixMonthsAgo = datetime.datetime.now().year * 12 + datetime.datetime.now().month - 6
                        tmpResult = []
                        if accountType == 'D1':
                            if accountState in ['1', '2', '4', '6', '7', '8']:
                                for i in PD01EH:
                                    # 还款状态
                                    state = i.get('PD01ED01')
                                    # 逾期（透支）总额
                                    ovduAmt = i.get('PD01EJ01')
                                    # 月份
                                    ovduMonth = i.get('PD01ER03')
                                    if ovduMonth in null_type_list:
                                        tmpResult.append(None)
                                        continue
                                    else:
                                        try:
                                            ovduMonthFact = float(ovduMonth[:4]) * 12 + float(ovduMonth[5:7]) if float(
                                                ovduMonth[5:7]) <= 12 else float(ovduMonth[5:6])
                                        except:
                                            tmpResult.append(None)
                                            continue
                                    if state not in null_type_list:
                                        if isfloat(state):
                                            if float(state) >= 1 and float(state) <= 7:
                                                if ovduMonthFact > monthSixMonthsAgo and ovduMonthFact <= monthToday:
                                                    tmpResult.append(float(state))
                                                else:
                                                    tmpResult.append(0)
                                            else:
                                                tmpResult.append(None)
                                        else:
                                            tmpResult.append(0)
                                    else:
                                        tmpResult.append(None)
                                tmpResult = filter(lambda x: x is not None, tmpResult)
                                # print tmpResult
                                if len(tmpResult) == 0:
                                    result1.append(None)
                                    result2.append(None)
                                else:
                                    result2.append(max(tmpResult))
                                    tmpResult = filter(lambda x: x == 1, tmpResult)
                                    result1.append(sum(tmpResult))
                            else:
                                result1.append(0)
                                result2.append(0)
                        elif accountType == 'R1':
                            if accountState in ['1', '2', '4', '5', '6', '8']:
                                for i in PD01EH:
                                    # 还款状态
                                    state = i.get('PD01ED01')
                                    # 逾期（透支）总额
                                    ovduAmt = i.get('PD01EJ01')
                                    # 月份
                                    ovduMonth = i.get('PD01ER03')
                                    if ovduMonth in null_type_list:
                                        tmpResult.append(None)
                                        continue
                                    else:
                                        try:
                                            ovduMonthFact = float(ovduMonth[:4]) * 12 + float(ovduMonth[5:7]) if float(
                                                ovduMonth[5:7]) <= 12 else float(ovduMonth[5:6])
                                        except:
                                            tmpResult.append(None)
                                            continue
                                    if state not in null_type_list:
                                        if isfloat(state):
                                            if float(state) >= 1 and float(state) <= 7:
                                                if ovduMonthFact > monthSixMonthsAgo and ovduMonthFact <= monthToday:
                                                    tmpResult.append(float(state))
                                                else:
                                                    tmpResult.append(0)
                                            else:
                                                tmpResult.append(None)
                                        else:
                                            tmpResult.append(0)
                                    else:
                                        tmpResult.append(None)
                                tmpResult = filter(lambda x: x is not None, tmpResult)
                                # print tmpResult
                                if len(tmpResult) == 0:
                                    result1.append(None)
                                    result2.append(None)
                                else:
                                    result2.append(max(tmpResult))
                                    tmpResult = filter(lambda x: x == 1, tmpResult)
                                    result1.append(sum(tmpResult))
                            else:
                                result1.append(0)
                                result2.append(0)
                        elif accountType == 'R4':
                            if accountState in ['1', '2', '4', '6', '8']:
                                for i in PD01EH:
                                    # 还款状态
                                    state = i.get('PD01ED01')
                                    # 逾期（透支）总额
                                    ovduAmt = i.get('PD01EJ01')
                                    # 月份
                                    ovduMonth = i.get('PD01ER03')
                                    if ovduMonth in null_type_list:
                                        tmpResult.append(None)
                                        continue
                                    else:
                                        try:
                                            ovduMonthFact = float(ovduMonth[:4]) * 12 + float(ovduMonth[5:7]) if float(
                                                ovduMonth[5:7]) <= 12 else float(ovduMonth[5:6])
                                        except:
                                            tmpResult.append(None)
                                            continue
                                    if state not in null_type_list:
                                        if isfloat(state):
                                            if float(state) >= 1 and float(state) <= 7:
                                                if ovduMonthFact > monthSixMonthsAgo and ovduMonthFact <= monthToday:
                                                    tmpResult.append(float(state))
                                                else:
                                                    tmpResult.append(0)
                                            else:
                                                tmpResult.append(None)
                                        else:
                                            tmpResult.append(0)
                                    else:
                                        tmpResult.append(None)
                                tmpResult = filter(lambda x: x is not None, tmpResult)
                                # print tmpResult
                                if len(tmpResult) == 0:
                                    result1.append(None)
                                    result2.append(None)
                                else:
                                    result2.append(max(tmpResult))
                                    tmpResult = filter(lambda x: x == 1, tmpResult)
                                    result1.append(sum(tmpResult))
                            else:
                                result1.append(0)
                                result2.append(0)
                        elif accountType == 'R2':
                            if accountState in ['1', '2', '3', '31', '5', '8']:
                                for i in PD01EH:
                                    # 还款状态
                                    state = i.get('PD01ED01')
                                    # 逾期（透支）总额
                                    ovduAmt = i.get('PD01EJ01')
                                    # 月份
                                    ovduMonth = i.get('PD01ER03')
                                    if ovduMonth in null_type_list:
                                        tmpResult.append(None)
                                        continue
                                    else:
                                        try:
                                            ovduMonthFact = float(ovduMonth[:4]) * 12 + float(ovduMonth[5:7]) if float(
                                                ovduMonth[5:7]) <= 12 else float(ovduMonth[5:6])
                                        except:
                                            tmpResult.append(None)
                                            continue
                                    if state not in null_type_list:
                                        if isfloat(state):
                                            if float(state) >= 1 and float(state) <= 7:
                                                if ovduMonthFact > monthSixMonthsAgo and ovduMonthFact <= monthToday:
                                                    tmpResult.append(float(state))
                                                else:
                                                    tmpResult.append(0)
                                            else:
                                                tmpResult.append(None)
                                        else:
                                            tmpResult.append(0)
                                    else:
                                        tmpResult.append(None)
                                tmpResult = filter(lambda x: x is not None, tmpResult)
                                # print tmpResult
                                if len(tmpResult) == 0:
                                    result1.append(None)
                                    result2.append(None)
                                else:
                                    result2.append(max(tmpResult))
                                    tmpResult = filter(lambda x: x == 1, tmpResult)
                                    result1.append(sum(tmpResult))
                            else:
                                result1.append(0)
                                result2.append(0)
                        elif accountType == 'R3':
                            if accountState in ['1', '2', '3', '31', '5', '8']:
                                for i in PD01EH:
                                    # 还款状态
                                    state = i.get('PD01ED01')
                                    # 逾期（透支）总额
                                    ovduAmt = i.get('PD01EJ01')
                                    # 月份
                                    ovduMonth = i.get('PD01ER03')
                                    if ovduMonth in null_type_list:
                                        tmpResult.append(None)
                                        continue
                                    else:
                                        try:
                                            ovduMonthFact = float(ovduMonth[:4]) * 12 + float(ovduMonth[5:7]) if float(
                                                ovduMonth[5:7]) <= 12 else float(ovduMonth[5:6])
                                        except:
                                            tmpResult.append(None)
                                            continue
                                    if state not in null_type_list:
                                        if isfloat(state):
                                            if float(state) >= 1 and float(state) <= 7:
                                                if ovduMonthFact > monthSixMonthsAgo and ovduMonthFact <= monthToday:
                                                    if float(state) > 3:
                                                        # 准贷记卡 逾期 - 3
                                                        tmpResult.append(float(state) - 3)
                                                    else:
                                                        tmpResult.append(0)
                                                else:
                                                    tmpResult.append(0)
                                            else:
                                                tmpResult.append(None)
                                        else:
                                            tmpResult.append(0)
                                    else:
                                        tmpResult.append(None)
                                tmpResult = filter(lambda x: x is not None, tmpResult)
                                # print tmpResult
                                if len(tmpResult) == 0:
                                    result1.append(None)
                                    result2.append(None)
                                else:
                                    result2.append(max(tmpResult))
                                    tmpResult = filter(lambda x: x == 1, tmpResult)
                                    result1.append(sum(tmpResult))
                            else:
                                result1.append(0)
                                result2.append(0)
                        else:
                            result1.append(0)
                            result2.append(0)
                            continue

            result1 = filter(lambda x: x is not None, result1)
            result2 = filter(lambda x: x is not None, result2)
            print result1, result2
            if len(result1) == 0 and len(result2) == 0:
                return u'缺失值'
            else:
                if len(result1) == 0:
                    Factor1 = 0
                else:
                    Factor1 = sum(result1)
                if len(result2) == 0:
                    Factor2 = 0
                else:
                    Factor2 = max(result2)

                if Factor1 > 3 or Factor2 > 1:
                    return 0
                else:
                    return 1


result = Ind_UnpaidOverdueCnt_6monCheck()
